﻿using AuthCenter.Domain;
using AuthCenter.ErorCode;
using AuthCenter.Infrastructure;
using AuthCenter_API.Read.Applications.Commands.RBAC;
using AuthCenter_API.Read.Dtos;
using MediatR;

namespace AuthCenter_API.Read.Applications.CommandHandlers.RBAC
{
    public class RoleMenuQueryCommandHandler : IRequestHandler<RoleMenuQueryCommand, APIResult<List<RoleMenuDto>>>
    {
        private readonly IBaseRepository<MenuModel> _menuRepository;
        private readonly IBaseRepository<RoleMenuModel> _RMRepository;

        public RoleMenuQueryCommandHandler(IBaseRepository<MenuModel> menuRepository, IBaseRepository<RoleMenuModel> rMRepository)
        {
            _menuRepository = menuRepository;
            _RMRepository = rMRepository;
        }

        public Task<APIResult<List<RoleMenuDto>>> Handle(RoleMenuQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<RoleMenuDto>> result = new APIResult<List<RoleMenuDto>>();
            result.Code = APIEnum.QuerySuccess;
            result.Message = APIEnum.QuerySuccess.Desc();
            var list = request.RoleId.Split(',').ToList();
            var menus=_RMRepository.GetAll();
            List<int> model=new List<int>();
            foreach (var item in list)
            {
                var mids=menus.Where(x=>x.RID==Convert.ToInt32(item)).Select(x=>x.MID).ToList();
                model.AddRange(mids);
            }
            var menuQuery = _menuRepository.GetAll().Where(x => x.IsDel == 0);
            var Data = Find(0, menuQuery.ToList(), model);
            result.Data = Data;
            return Task.FromResult(result);
        }
        public List<RoleMenuDto> Find(int id, List<MenuModel> ids, List<int> mid)
        {
            var res = ids.Where(x => x.PID == id && mid.Contains(x.MenuId)).ToList();
            List<RoleMenuDto> list = new List<RoleMenuDto>();
            foreach (var item in res)
            {
                list.Add(new RoleMenuDto()
                {
                    MenuName = item.MenuName,
                    Url = item.Url,
                    Children = Find(item.MenuId, ids, mid)
                });
            }
            return list;
        }
    }
}
